package com.koo.modules.sale.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.PageUtils;
import com.koo.common.utils.Query;
import com.koo.modules.sale.dao.SalePayOrderDao;
import com.koo.modules.sale.entity.SalePayOrderEntity;
import com.koo.modules.sale.entity.vo.PayQueryVo;
import com.koo.modules.sale.service.SalePayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SalePayOrderServiceImpl extends ServiceImpl<SalePayOrderDao, SalePayOrderEntity> implements SalePayOrderService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        
        QueryWrapper<SalePayOrderEntity> wrapper = new QueryWrapper<>();

        Object dataForm = params.get("dataForm");
        if (dataForm != null) {
            PayQueryVo queryVo = JSON.parseObject(dataForm.toString(), PayQueryVo.class);
            String queryDates = queryVo.getQueryDates();
            String payType = queryVo.getPayType();
            String saleType = queryVo.getSaleType();
            String key = queryVo.getKey();
            String queryField = queryVo.getQueryField();

            if (queryVo != null) {
                if (MyStrUtil.isNotEmpty(queryDates)) {
                    String[] queryDateArr = queryDates.split(",");
                    String startDate = queryDateArr[0];
                    String endDate = queryDateArr[1];
                    wrapper.ge(MyStrUtil.isNotEmpty(startDate), "pay_date", startDate);
                    wrapper.le(MyStrUtil.isNotEmpty(endDate), "pay_date", endDate);
                }
                wrapper.eq(payType != null, "IFNULL(pay_type, 0)", payType);
                wrapper.eq(saleType != null, "IFNULL(sale_type, 0)", saleType);
                wrapper.like(StringUtils.isNotBlank(queryField) && StringUtils.isNotBlank(key), queryField, key);
            }
        }
        IPage<SalePayOrderEntity> page = new Query<SalePayOrderEntity>().getPage(params);
        page = baseMapper.selectPage(page, wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<SalePayOrderEntity> listByStoreId(Long storeId) {
        LambdaQueryWrapper<SalePayOrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MyStrUtil.isNotEmpty(storeId), SalePayOrderEntity::getStoreId, storeId);
        return this.list(wrapper);
    }
}